<template>
  <div class="login">
    <el-form class="login-form" ref="login-form" :model="user" :rules="formRules" >
      <el-form-item prop="mobile">
        <el-input v-model="user.mobile" placeholder="请输入手机号" ></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="user.code" placeholder="请输入验证码" ></el-input>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox v-model="user.agree">我已阅读并同意用户协议和隐私</el-checkbox>
      </el-form-item>
      <el-form-item >
        <el-button class="login-btn" type="primary" :loading="loginLoading" 
        @click="onLogin" >登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>

import { login } from '@/api/user'
  export default {
    data() {
      return {
        user: {
          mobile: '13911111111', // 手机号
          code: '246810', // 验证码
          agree: false // 是否同意协议
        },
        loginLoading:false,
        formRules:{
          mobile: [
            { required: true, message: '请输入手机号不能为空', trigger: 'change' },
             { pattern:/^1[3|5|7|9]\d/, message: '请输入正确手机号格式', trigger: 'change' },
          ],
          code: [
            { required: true, message: '请验证码不能为空', trigger: 'change' },
             { pattern:/^\d{6}$/, message: '请输入六位验证码', trigger: 'change' },
          ],
          agree:[
            { validator:( rule, value, callback)=>{
              if(value){
                callback()
              }else{
                callback(new Error('请同意用户协议'))
              }
             }
            }
          ],
        }
      }
    },
    methods: {
      //登录
        onLogin() {
        this.$refs['login-form'].validate((valid)=>{
          if(!valid){
            return
          }else{
           this.login()
          }
        })
        
        
      },
      //封装登录请求接口
      async login(){
        this.loginLoading=true
        try{
          const res = await login(this.user)
          // console.log(res);
          this.$message.success('登陆成功')

          //将登录得到的token放到本地存储
          //本地存储只能存储对象
          window.localStorage.setItem('user',JSON.stringify(res.data.data))

          this.$router.push('/')
        }catch(err){
          this.$message.error('登陆失败,手机号或验证码错误')
        }
          this.loginLoading=false
      }
    }
  }
</script>
<style lang ="scss" scoped>
.login{
  position: fixed;
  left:0;
  right: 0;
  top:0;
  bottom:0;
  display: flex;
  justify-content: center;
  align-items: center;
  background:url('./login_bg.jpg') no-repeat;
  background-size: 'cover';
  .login-form{
    background-color: #fff;
    padding: 50px;
    min-width: 300px;
    .login-btn{
      width: 100%;
    }
  }
}
</style>